<?php

namespace App\Admin\Controllers\Dedusting;

use App\Models\DedustingPointRange;
use App\Models\DedustingDevicePoint;
use App\Models\DedustingDevice;
use App\Http\Controllers\Controller;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Callout;
use Illuminate\Support\Facades\DB;
use Dcat\Admin\Form;
use Dcat\Admin\Admin;
use Dcat\Admin\Show;
use Illuminate\Http\Request;
use App\Handlers\IotCardHandler;

class PointRangeController extends Controller
{
    public function index(Content $content)
    {
        return $content
            ->header('点位阈值范围')
            ->description('')
            ->body($this->grid());
    }

    protected function grid()
    {
        return new Grid(DedustingPointRange::with(['device']), function (Grid $grid) {
            $grid->column('point', '点位')->using(DedustingDevicePoint::POINTS);
            $grid->column('min', '最小值');
            $grid->column('max','最大值');

            $grid->disableCreateButton();
            $grid->disableDeleteButton();
            $grid->disableViewButton();
        });
    }

    public function update($id){
        return $this->form()->update($id);
    }
    public function store(){
        return $this->form()->store();
    }

    public function create(Content $content){
        return $content
            ->title('新建点位阈值范围')
            ->description('创建')
            ->body($this->form());
    }

    public function form(){
        return Form::make(new DedustingPointRange(), function (Form $form) {
            $form->hidden('point');
            $form->text('min', '最小值')->required();
            $form->text('max', '最大值')->required();
            $form->hidden('user_id')->value(Admin::user()->id);

            $form->saving(function (Form $form) {
                $form->user_id = Admin::user()->id;
            });

            //处理缓存
            $form->saved(function (Form $form, $result) {
                DedustingPointRange::setCache($form->point, $form->min, $form->max);
                return;
            });

            $form->deleted(function (Form $form, $result) {
                $data = $form->model()->toArray();
                if (! $result) {
                    return $form->response()->error('数据删除失败');
                }

                foreach ($data as $one) {
                    DedustingPointRange::delCache($one['device_id'], $one['point'], $one['condition']);
                }
                return;
            });
        });
    }

    public function edit($id,Content $content){
        $range = DedustingPointRange::find($id);
        return $content
            ->title(DedustingDevicePoint::POINTS[$range->point])
            ->description('编辑')
            ->body($this->form()->edit($id));
    }
}